"""Property API endpoints."""

from __future__ import annotations

from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

# from pydantic import BaseModel, Field  # 未使用，已注释

from ...deps import get_db, get_current_user
from ....models.user import User
from ....schemas.property import (
    PropertyCreate,
    PropertyUpdate,
    PropertyOut,
    PropertyListOut,
)
from ....schemas.common import BulkDeleteRequest, BulkOperationResponse
from ....services.property_service import PropertyService

router = APIRouter(prefix="/properties", tags=["properties"])


# 为properties创建专用别名，保持API兼容性
class PropertyBulkDeleteRequest(BulkDeleteRequest):
    """批量删除房源请求."""

    pass


@router.post(
    "/",
    response_model=PropertyOut,
    status_code=status.HTTP_201_CREATED,
    summary="创建房源",
)
def create_property(property_data: PropertyCreate, db: Session = Depends(get_db)) -> PropertyOut:
    """
    创建新房源。

    - **community_name**: 小区名称（必填）
    - **address**: 详细地址（必填）
    - **room_number**: 房号（必填）
    - **layout**: 户型，如"2室1厅"（必填）
    - **rent_price**: 租金（元/月，必填）
    - **landlord_phone**: 房东电话（必填）
    """
    service = PropertyService(db)

    # Check for duplicate room in same community
    is_duplicate = service.check_duplicate_room(
        property_data.community_name, property_data.room_number
    )
    if is_duplicate:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=(
                f"房号 {property_data.room_number} 在小区 {property_data.community_name} 已存在"
            ),
        )

    try:
        return service.create_property(property_data)
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e


@router.get("/", response_model=PropertyListOut, summary="获取房源列表")
def get_properties(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    community_name: Optional[str] = Query(None, description="小区名称（模糊搜索）"),
    property_status: Optional[str] = Query(None, description="房源状态"),
    min_price: Optional[int] = Query(None, ge=0, description="最低租金"),
    max_price: Optional[int] = Query(None, ge=0, description="最高租金"),
    db: Session = Depends(get_db),
) -> PropertyListOut:
    """
    获取房源列表（分页）。

    支持筛选条件：
    - 小区名称（模糊匹配）
    - 房源状态
    - 租金范围
    """
    service = PropertyService(db)
    skip = (page - 1) * page_size

    try:
        items, total = service.get_properties(
            skip=skip,
            limit=page_size,
            community_name=community_name,
            status=property_status,
            min_price=min_price,
            max_price=max_price,
        )

        return PropertyListOut(total=total, items=items, page=page, page_size=page_size)
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e


@router.get("/{property_id}", response_model=PropertyOut, summary="获取房源详情")
def get_property(property_id: int, db: Session = Depends(get_db)) -> PropertyOut:
    """获取指定房源的详细信息。"""
    service = PropertyService(db)

    property_data = service.get_property(property_id)
    if not property_data:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"房源 ID {property_id} 不存在",
        )

    return property_data


@router.put("/{property_id}", response_model=PropertyOut, summary="更新房源信息")
def update_property(
    property_id: int,
    property_data: PropertyUpdate,
    db: Session = Depends(get_db),
) -> PropertyOut:
    """更新房源信息。"""
    service = PropertyService(db)

    # Check for duplicate if room_number or community_name is being updated
    update_dict = property_data.model_dump(exclude_unset=True)
    if "room_number" in update_dict or "community_name" in update_dict:
        # Get current property
        current_property = service.get_property(property_id)
        if not current_property:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"房源 ID {property_id} 不存在",
            )

        community = update_dict.get("community_name", current_property.community_name)
        room = update_dict.get("room_number", current_property.room_number)

        is_duplicate = service.check_duplicate_room(community, room, property_id)
        if is_duplicate:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=(f"房号 {room} 在小区 {community} 已存在"),
            )

    updated_property = service.update_property(property_id, property_data)
    if not updated_property:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"房源 ID {property_id} 不存在",
        )

    return updated_property


@router.delete(
    "/{property_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="软删除房源（可恢复）",
    response_model=None,
)
def delete_property(
    property_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> None:
    """软删除指定房源（可恢复）。"""
    service = PropertyService(db)

    deleted = service.delete_property(property_id, current_user.id)
    if not deleted:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"房源 ID {property_id} 不存在",
        )


@router.post(
    "/{property_id}/restore",
    response_model=PropertyOut,
    summary="恢复已删除的房源",
)
def restore_property(
    property_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> PropertyOut:
    """恢复已软删除的房源。"""
    service = PropertyService(db)

    restored = service.restore_property(property_id)
    if not restored:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"房源 ID {property_id} 不存在或未被删除",
        )

    # Fetch and return restored property
    property_data = service.get_property(property_id)
    if not property_data:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"房源 ID {property_id} 不存在",
        )
    return property_data


@router.post(
    "/bulk-delete",
    response_model=BulkOperationResponse,
    summary="批量软删除房源",
)
def bulk_delete_properties(
    payload: BulkDeleteRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> BulkOperationResponse:
    """批量软删除房源记录（最多50个）.

    请求体示例:
    ```json
    {
        "property_ids": [1, 2, 3, 4, 5]
    }
    ```

    返回示例:
    ```json
    {
        "success": 4,
        "failed": 0,
        "not_found": 1,
        "message": "批量删除完成：成功4条，未找到1条"
    }
    ```
    """
    service = PropertyService(db)
    # Convert str IDs to int IDs
    property_ids = [int(id) for id in (payload.property_ids or [])]
    result = service.bulk_soft_delete(property_ids, current_user.id)

    message = f"批量删除完成：成功{result['success']}条"
    if result["not_found"] > 0:
        message += f"，未找到{result['not_found']}条"

    return BulkOperationResponse(
        success=bool(result["success"]),
        message=message,
        processed_count=(result["success"] + result["failed"] + result["not_found"]),
        failed_count=result["failed"],
        failed=result["failed"],
        not_found=result["not_found"],
    )


@router.post(
    "/bulk-restore",
    response_model=BulkOperationResponse,
    summary="批量恢复已删除房源",
)
def bulk_restore_properties(
    payload: BulkDeleteRequest,  # 复用相同的Schema
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> BulkOperationResponse:
    """批量恢复已删除的房源记录（最多50个）.

    请求体示例:
    ```json
    {
        "property_ids": [1, 2, 3]
    }
    ```

    返回示例:
    ```json
    {
        "success": 3,
        "failed": 0,
        "not_found": 0,
        "message": "批量恢复完成：成功3条"
    }
    ```
    """
    service = PropertyService(db)
    # Convert str IDs to int IDs
    property_ids = [int(id) for id in (payload.property_ids or [])]
    result = service.bulk_restore(property_ids)

    message = f"批量恢复完成：成功{result['success']}条"
    if result["not_found"] > 0:
        message += f"，未找到或未删除{result['not_found']}条"

    return BulkOperationResponse(
        success=bool(result["success"]),
        message=message,
        processed_count=(result["success"] + result["failed"] + result["not_found"]),
        failed_count=result["failed"],
        failed=result["failed"],
        not_found=result["not_found"],
    )
